package com.liangdemo.web.token;


import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Repository;

import java.util.Date;

/**
 * @author Mr.Liang
 * @date 2022/5/12 15:31
 */

@Repository
public class JwtUtils {
    //签名私钥
    @Value("${jwt.config.key}")
    private String key;
    //签名失效时间
    @Value("${jwt.config.failureTime}")
    private Long failureTime;

    /**
     * 设置认证token
     *
     * @param id      用户登录ID
     * @param subject 用户登录名
     * @return
     */
    public String createJwt(Long id, String subject) {

        //1、设置失效时间啊
        long now = System.currentTimeMillis();  //毫秒
        long exp = now + failureTime;

        //2、创建JwtBuilder
        JwtBuilder jwtBuilder = Jwts.builder().setId(String.valueOf(id)).setSubject(subject)
                .setIssuedAt(new Date())
                //设置签名防止篡改
                .signWith(SignatureAlgorithm.HS256, key);

        //3、根据map设置claims
//        for (Map.Entry<String, Object> entry : map.entrySet()) {
//            jwtBuilder.claim(entry.getKey(), entry.getValue());
//        }
        jwtBuilder.setExpiration(new Date(exp));

        //4、创建token
        String token = jwtBuilder.compact();
        return token;
    }

    /**
     * 解析token
     *
     * @param token
     * @return
     */
    public Claims parseJwt(String token) {
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException e) {
            claims = e.getClaims();
        }
        return claims;
    }

    /**
     * 判断token是否过期
     * true 未过期， false 过期
     *
     * @param token
     * @return
     */
    public Boolean isTokenExpired(String token) {
        Claims claims = this.parseJwt(token);
        Date date = claims.getExpiration();
        return ! new Date(System.currentTimeMillis()).after(date);
    }



}